/*
 * @Author: 一路向阳 tt_sunzhenfeng@163.com
 * @Date: 2024-02-29 23:27:54
 * @LastEditors: 一路向阳 tt_sunzhenfeng@163.com
 * @LastEditTime: 2024-03-13 21:12:59
 * @FilePath: \utils_react_manager\server\controller\wordController.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const DB = require('../modules/db');
const useRandomData = require('../utils/useRandomData');
const useTimeDiff = require('../utils/useTimeDiff');


// 单词列表
const wordList = async ctx => {
  try {
    const { pageNo, pageSize, source, name } = ctx.request.body;
    // 获取列表
    const sql = 'select * from word';
    const wordList = await DB.query(sql);

    // 条件筛选
    const result = wordList.filter(item => {
      // 来源&单词
      if (source && name) {
        return source?.indexOf(item?.source) !== -1 && name?.indexOf(item?.name) !== -1;
      }
      // 来源
      if (source) {
        return source?.indexOf(item?.source) !== -1;
      }
      // 单词
      if (name) {
        return name?.indexOf(item?.name) !== -1 || name?.indexOf(item?.explain) !== -1;
      }
      return item;
    });

    // 开始
    const start = (pageNo - 1) * pageSize;
    // 结束
    const end = start + pageSize;
    // 分页截取及排序
    const data = result.sort((a, b) => a.id - b.id).slice(start, end);

    ctx.body = {
      success: true,
      code: 200,
      msg: '获取成功',
      data,
      count: result.length || 0
    };
  }
  catch (error) {
    ctx.throw(error);
  }
};

// 测试数据
const learnWord = async ctx => {
  try {
    const { source, count = 10 } = ctx.request.body;
    const sql = 'select * from word';
    const wordList = await DB.query(sql);

    const learnList = wordList.filter(item => {
      const { days, hours } = useTimeDiff(item.createTime, item.updateTime);
      // 数据来源
      if (source) {
        return item?.source === source;
      }

      // 新增单词
      if (!item?.count) {
        return item;
      }
      
      // 记忆周期
      if (hours >= 1 || days >= 1 || days >= 2 || days >= 6 || days >= 14 || days >= 30) {
        return item;
      }
    });

    // 输出随机选定的数据项
    const  result = useRandomData(learnList.sort((a, b) => a.count - b.count), [], count);

    ctx.body = {
      success: true,
      code: 200,
      msg: '获取成功',
      data: result,
      count: result.length || 0
    };
  }
  catch (error) {
    ctx.throw(error);
  }
};

// 新增单词
const addWord = async ctx => {
  try {
    const { ...otherParams } = ctx.request.body;

    const wordList = await DB.query(`select * from word`);

    if (wordList.some(item => item.name === otherParams?.name)) {
      ctx.body = {
        success: false,
        code: 200,
        msg: '该单词已存在'
      };
      return;
    }

    const values = [];

    for (const key in otherParams) {
      values.push(`'${otherParams?.[key]}'`);
    }

    const sql = 'INSERT INTO word (`name`, `voice`, `explain`, `source`, `createTime`, `updateTime`)' + ` VALUES (${values.join(', ')});`;
    
    await DB.query(sql);

    ctx.body = {
      success: true,
      code: 200,
      msg: '添加成功'
    };
  }
  catch (error) {
    ctx.throw(error);
  }
};
// 更新接口
const updateWord = async ctx => {
  try {
    const { id, name, voice, explain, source, updateTime} = ctx.request.body;
    
    const sql = 'UPDATE word SET `name` = ' + `'${name}', ` + '`voice` = ' + `'${voice}', ` + '`explain` = ' + `'${explain}', ` + '`source` = ' + `'${source}', ` + '`updateTime` = ' + `'${updateTime}'` + ` WHERE id = ${id}`;
    console.log(sql);
    await DB.query(sql);

    ctx.body = {
      success: true,
      code: 200,
      msg: '更新成功'
    };
  }
  catch (error) {
    ctx.throw(error);
  }
};
// 熟悉单词
const count = async ctx => {
  try {
    const { id, type, count, updateTime } = ctx.request.body;

    const sql = `UPDATE word SET count = ${count}, updateTime = ${updateTime} where id = ${id};`

    await DB.query(sql);
    
    ctx.body = {
      success: true,
      code: 200,
      msg: type === 'familiar' ? '记忆又深刻了一步' : '又陌生了，改加强记忆了'
    };
  }
  catch (error) {
    ctx.throw(error);
  }
}

module.exports = {
  wordList,
  learnWord,
  addWord,
  updateWord,
  count
};